﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml;
using System.Xml.Serialization;
using kangsuce.Common;
using kangsuce.Model;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Entities;

namespace kangsuce.Admin.Controllers
{
    public class BaseController : Controller
    {
        private BLL.MenuBLL menuBLL = new BLL.MenuBLL();

        public KSC_WxConfig wxConfig => Common.Common.GetWxConfigText(Server.MapPath("/config/weixin.xml"));

        public KSC_SysUser userInfo => GetSysUser();

        public string access_token => GetAccessToken();

        private KSC_SysUser GetSysUser()
        {
            KSC_SysUser model = null;
            HttpCookie cookie = HttpContext.Request.Cookies["userId"];
            if (cookie != null && cookie.Value != "null")
            {
                if (Session["user"] == null)
                {
                    int userId = Convert.ToInt32(cookie.Value);
                    BLL.SysUserBLL sysUserBLL = new BLL.SysUserBLL();
                    model = sysUserBLL.GetModel(p => p.userId == userId, true);
                }
                else
                {
                    model = Session["user"] as KSC_SysUser;
                }
            }
            return model;
        }

        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <returns></returns>
        private string GetAccessToken()
        {
            return AccessTokenContainer.TryGetAccessToken(wxConfig.AppId, wxConfig.AppSecret, false);
        }


        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            string url = filterContext.RequestContext.HttpContext.Request.Path.ToLower();
            if (!url.Contains("/Home/Login".ToLower()) && !url.Contains("/Home/LoginValidate".ToLower()))
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    if (userInfo == null)
                    {
                        filterContext.Result = Json(new { result = "error", msg = "用户信息丢失，请重新登录" },
                            JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    if (userInfo == null)
                    {
                        filterContext.Result =
                            new RedirectResult("/Home/Login?backUrl=" +
                                               filterContext.RequestContext.HttpContext.Request.RawUrl);
                    }
                    else
                    {
                        if (userInfo.userType != 1)
                        {
                            if (url != "/" && url != "/Home/Desktop".ToLower() && url != "/Home/Index".ToLower())
                            {
                                List<KSC_UserRole> urList = userInfo.userRoleList;
                                List<KSC_Menu> menuList = menuBLL.GetList(p => true);
                                List<string> menuUrls = (from item in urList
                                                         from item1 in item.rolePermissionList
                                                         select menuList.FirstOrDefault(p => p.menuId == item1.menuId).menuUrl.ToLower()).ToList();
                                if (!menuUrls.Contains(url))
                                {
                                    filterContext.RequestContext.HttpContext.Response.Redirect("/noAuthorize.html");
                                    filterContext.RequestContext.HttpContext.Response.End();
                                }
                            }
                        }
                    }
                }
            }
            base.OnAuthorization(filterContext);
        }

    }
}